import axios, { AxiosRequestConfig, AxiosError, AxiosResponse, AxiosInstance } from 'axios';
import { message } from 'ant-design-vue';
import userStore from '@/store/user';

// let baseURL = process.env.NODE_ENV == 'development' ? '/api' : '/api';
const service: AxiosInstance = axios.create({
    baseURL: '/api',
    timeout: 1000 * 30
});

//发送请求配置
service.interceptors.request.use((config: any) => {
    const userInfo = userStore();
    let { token } = userInfo;
    config.headers = {
        'authorization': token ? `Bearer ${token}` : ''
    }
    return config;
}, (error: AxiosError) => {
    return Promise.reject(error)
});

//响应结果处理
service.interceptors.response.use((response: AxiosResponse) => {
    return response.data;
}, (error: any) => {
    if (error && error.response) {
        let msg = error.response?.data?.message || error.message
        switch (error.response.status) {
            case 400:
                message.error(msg)
                break;
            case 401:
                message.error(msg)
                break;
            case 403:
                const userInfo = userStore();
                message.error(msg || 'token失效')
                userInfo.updateToken('')
                window.location.replace('/login');
                break;
            default:
                message.error(msg)
                break;
        }
    }
    return Promise.reject(error);
});

export const http = {
    get<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
        return service.get(url, config)
    },
    delete<T = any>(url: string, config?: AxiosRequestConfig<T>): Promise<T> {
        return service.delete(url, config)
    },
    post<T = any>(url: string, data?: object, config?: AxiosRequestConfig): Promise<T> {
        return service.post(url, data, config)
    },
    put<T = any>(url: string, data?: object, config?: AxiosRequestConfig): Promise<T> {
        return service.put(url, data, config)
    }
}

export default service;
